package com.jim.jeecg.imvc2.core.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.jim.jeecg.imvc2.core.annotation.Controller;
import com.jim.jeecg.imvc2.core.annotation.Forward;
import com.jim.jeecg.imvc2.core.annotation.RequestMapping;
import com.jim.jeecg.imvc2.core.form.AnnotationBean;

public class AnnotationUtil {

	public static Map<String, AnnotationBean> setStrutsAnnotation(
			String packagesToScan) {
		// TODO Auto-generated method stub
		String[] packages=packagesToScan.split(",");
		Map<String,AnnotationBean> rMap=new HashMap<String, AnnotationBean>();
		for(String pack : packages){
			if(StringUtils.isNotEmpty(pack)){
			   Set<Class<?>> classSet = PackagesToScanUtil.getClasses(pack);
			   for(Class<?> actionClass : classSet){
				   String strPath="";
				   if(actionClass.isAnnotationPresent(Controller.class)){
					   AnnotationBean annotationBean=new AnnotationBean();
					   annotationBean.setActionType(actionClass.getName());
					   Controller controller= actionClass.getAnnotation(Controller.class);
					   //获取请求根路径
					   strPath=controller.value();
					   
					     Method[] methods=actionClass.getMethods();
					     for (Method method : methods) {
							if(method.isAnnotationPresent(RequestMapping.class))
							{
								 RequestMapping annoRequestMapping=method.getAnnotation(RequestMapping.class);
								 if(StringUtils.isNotEmpty(annoRequestMapping.path()))
								 {
									 strPath=strPath+"//"+annoRequestMapping.path();
								 }
								 annotationBean.setFormClass(annoRequestMapping.form());
			
							     if(method.isAnnotationPresent(Forward.class))
							     {
							    	 Map<String,String> actionForward=new HashMap<String,String>();
							    	 Forward annosForward= method.getAnnotation(Forward.class);
							    	 String[] results=annosForward.result();
							    	 String[] redirctUrls=annosForward.redirctUrl();
							    	 for (int i = 0; i < results.length; i++) {
							    		 actionForward.put(results[i], redirctUrls[i]);
									 }
							    	 annotationBean.setActionForward(actionForward); 
							     }
							     rMap.put(strPath, annotationBean);
							}
						}
					   }
				   }
			   }
			}
		
		return rMap;
	}
}
